#include "TcpServer.h"
namespace mpgl_engine{ namespace application{ namespace net {

	TcpServer::TcpServer(GlConsole* console,
		io_service* ioService,
		uint maxConnections) :
		TcpSession(console, ioService,
		TcpSessionType::SERVER, maxConnections)
	{
#if (TCP_SESSION_DEBUG >= 1)
		if (m_console != NULL){
			string msg = NetworkDefines::CONSOLE_MSG_PREFIX;
			msg += " TcpServer :: Constructed ";
			m_console->WriteMessage(msg);
		}
#endif
	}

	/*---------------------------------------------------
	------------------------------------------------------*/

	void TcpServer::SetAcceptor(){
		if (m_ioService != NULL){
			m_acceptor =
				new tcp::acceptor(*m_ioService, tcp::endpoint(tcp::v4(),
				NetworkDefines::TCP_DEF_PORT));

#if (TCP_SESSION_DEBUG >= 1)
			if (m_console != NULL){
				string msg = NetworkDefines::CONSOLE_MSG_PREFIX;
				msg += " TcpServer :: Acceptor Set ";
				m_console->WriteMessage(msg);
			}
#endif
		}
	}

	/*---------------------------------------------------
	------------------------------------------------------*/

	void TcpServer::HandleAccept(TcpConnection* newConnection,
		const boost::system::error_code& error)
	{
		if (!error)
		{
#if (TCP_SESSION_DEBUG >= 1)
			if (m_console != NULL){
				string msg = NetworkDefines::CONSOLE_MSG_PREFIX;
				msg += " TcpServer :: Client Accepted ";
				m_console->WriteMessage(msg);
			}
#endif
			m_connections.push_back(newConnection);
		}
		else
		{
#if (TCP_SESSION_DEBUG >= 1)
			if (m_console != NULL){
				string msg = NetworkDefines::CONSOLE_MSG_PREFIX;
				msg += " TcpServer :: Failed to Accept Client ";
				m_console->WriteMessage(msg);
			}
#endif
		}
		StartAccept();
	}

	/*---------------------------------------------------
	------------------------------------------------------*/

	void TcpServer::StartAccept(){
		if (m_ioService != NULL)
		{
			if (m_connections.size() < m_maxConnections)
			{
#if (TCP_SESSION_DEBUG >= 1)
				if (m_console != NULL){
					string msg = NetworkDefines::CONSOLE_MSG_PREFIX;
					msg += " TcpServer :: Starting Async Accept ";
					m_console->WriteMessage(msg);
				}
#endif

				TcpConnection* con = NULL;
				con = new TcpConnection(*m_ioService);
				m_acceptor->async_accept(con->socket(),
					boost::bind(&TcpServer::HandleAccept, this,
					con, boost::asio::placeholders::error));
			}
		}
	}


}}}